package com.dsl.dslsuzhou.engine;


import com.dsl.dslsuzhou.model.entity.dsl.TimeSpec;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 时间范围计算工具
 */
public class TimeRangeCalc {
    
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    
    /**
     * 根据时间窗口配置计算时间范围
     */
    public static TimeRange calculate(TimeSpec.Window window) {
        if (window == null) {
            throw new IllegalArgumentException("Time window cannot be null");
        }
        
        String type = window.getType();
        if ("today".equals(type)) {
            return calculateToday();
        } else if ("relative".equals(type)) {
            return calculateRelative(window.getUnit(), window.getValue());
        } else if ("between".equals(type)) {
            return calculateBetween(window.getBegin(), window.getEnd());
        } else {
            throw new IllegalArgumentException("Unsupported time window type: " + type);
        }
    }
    
    /**
     * 计算今天的时间范围
     */
    private static TimeRange calculateToday() {
        LocalDate today = LocalDate.now();
        LocalDateTime start = today.atStartOfDay();
        LocalDateTime end = today.plusDays(1).atStartOfDay();
        return new TimeRange(start, end);
    }
    
    /**
     * 计算相对时间范围
     */
    private static TimeRange calculateRelative(String unit, Integer value) {
        if (value == null || value <= 0) {
            throw new IllegalArgumentException("Relative time value must be positive");
        }
        
        LocalDateTime end = LocalDateTime.now();
        LocalDateTime start;
        
        if ("day".equals(unit)) {
            start = end.minusDays(value);
        } else if ("month".equals(unit)) {
            start = end.minusMonths(value);
        } else {
            throw new IllegalArgumentException("Unsupported time unit: " + unit);
        }
        
        return new TimeRange(start, end);
    }
    
    /**
     * 计算指定时间范围
     */
    private static TimeRange calculateBetween(String begin, String end) {
        if (begin == null || end == null) {
            throw new IllegalArgumentException("Begin and end dates cannot be null");
        }
        
        try {
            LocalDate beginDate = LocalDate.parse(begin, DATE_FORMATTER);
            LocalDate endDate = LocalDate.parse(end, DATE_FORMATTER);
            
            LocalDateTime start = beginDate.atStartOfDay();
            LocalDateTime endTime = endDate.atStartOfDay(); // 右开区间
            
            return new TimeRange(start, endTime);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid date format, expected yyyy-MM-dd", e);
        }
    }
}
